package com.cjt.common.exception;


import com.cjt.common.lang.R;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 解决Filter中异常返回值问题
 * @author : lzb
 * @date: 2022-05-10 09:16
 */
@RestController
public class FilterErrorController extends BasicErrorController {

    public FilterErrorController(ServerProperties serverProperties) {
        super(new DefaultErrorAttributes(), serverProperties.getError());
    }

    @Override
    @RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity error(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request, ErrorAttributeOptions.defaults());
        //可以通过断点调试来查看body中的信息
        HttpStatus status = getStatus(request);
        R response = new R();
        response.setCode(status.value());
        response.setMsg(String.valueOf(body.get("error")));
        return new ResponseEntity<>(response,status);
    }

}
